﻿/*
 * @author: wizardc
 */

using System;
using System.Collections.Generic;
using MessagePack.Formatters;
using MessagePack.Internal;
using Unity.Mathematics;

namespace MessagePack.Resolvers
{
    /// <summary>
    /// 扩展使 MessagePack 支持 Mathmatics 库
    /// 注：未提供完整的所有类型，有需求请自行扩展
    /// </summary>
    public class UnityMathmaticsResolver : IFormatterResolver
    {
        public static readonly UnityMathmaticsResolver Instance = new UnityMathmaticsResolver();

        private UnityMathmaticsResolver()
        {
        }

        public IMessagePackFormatter<T> GetFormatter<T>()
        {
            return FormatterCache<T>.Formatter;
        }

        private static class FormatterCache<T>
        {
            public static readonly IMessagePackFormatter<T> Formatter;

            static FormatterCache()
            {
                Formatter = (IMessagePackFormatter<T>)UnityMathmaticsResolverGetFormatterHelper.GetFormatter(typeof(T));
            }
        }
    }
}

namespace MessagePack.Internal
{
    internal static class UnityMathmaticsResolverGetFormatterHelper
    {
        private static readonly Dictionary<Type, object> FormatterMap = new Dictionary<Type, object>()
        {
            { typeof(float2), Float2Formatter.Instance },
            { typeof(float4x4), Float4x4Formatter.Instance },
        };

        internal static object GetFormatter(Type t)
        {
            object formatter;
            if (FormatterMap.TryGetValue(t, out formatter))
            {
                return formatter;
            }
            if (typeof(Type).IsAssignableFrom(t))
            {
                return typeof(TypeFormatter<>).MakeGenericType(t).GetField(nameof(TypeFormatter<Type>.Instance)).GetValue(null);
            }
            return null;
        }
    }
}
